<?php

namespace App\System\Base\Services;

use App\Exceptions\Customize\ParamsException;
use App\System\Base\Helpers\Traits\SinglePattern;
use App\System\Base\Model\BaseSmsCode;
use App\System\Log\Model\LogSms;
use Illuminate\Support\Facades\Request;

class SmsService extends Service
{
    use SinglePattern;

    /** 发送验证码方法
     * @param $mobile 手机号
     * @return bool|int  发送成功返回验证码 否则返回false
     * @auther kalv1n
     */
    public function SmsSend($mobile,$type)
    {
        $singleSender = new SmsSenderService();
        $code = mt_rand(100000, 999999);
        $set = ['code'=>$code,
                'type'=>$type,
                'expire'=>date("Y-m-d H:i:s",time()+config("global.smsExpire")),
                'status'=>2,
                'mobile'=>$mobile,
               ];
        $id = BaseSmsCode::create($set);
//        符合图形验证码才允许发送短信
       $cache= \Cache::get(Request::get('s'));
//        if ($captchaCode == $cache))
        if(!$id)
        {
            return ['s'=>'1000','d'=>'短信发送失败，服务异常错误，请稍后在试'];
        }
        $msg = "{$code}为您的验证码，请于10分钟内填写。如非本人操作，请忽略本短信。";

        if(config('app.debug') != true)
        {
            $result = $singleSender->send(0, "86", $mobile, $msg);
            $rsp = json_decode($result);
        }
        else
        {
            $rsp = (object) array('errmsg'=>'OK');
        }
        if ($rsp->errmsg == 'OK')
        {
//            记录log
//            $this->generateLog($mobile,$type,$msg);
            if(config('app.debug') == true)
            {
                $res['code'] = $code;
            }
            return $res;
        }

        return ['s'=>'1000','d'=>'短信发送失败，服务异常错误，请稍后在试'];
    }

    /** 验证验证码方法
     * @param $mobile 手机号
     * @param $code 验证码
     * @return  成功返回true 失败/无记录分别抛出异常
     * @auther 李建鸿
     */
    public function VerifySmsCode($mobile, $code,$type)
    {
        $code_info =BaseSmsCode::where('mobile',$mobile)
            ->where("code",$code)
            ->where('type',$type)
            ->where("status",2)
            ->orderBy("id",'desc')
            ->first();
        if(!$code_info)
        {
            return ['s'=>'1003','d'=>"验证码错误"];
        }
        elseif($code_info->expire < date("Y-m-d H:i:s"))
        {
            return ['s'=>'10000','d'=>"验证码已失效，请重新发送"];
        }

        BaseSmsCode::where('id',$code_info->id)->update(['status'=>1]);

        return ['s'=>'0','d'=>"操作成功",'id'=>$code_info->id];
    }

    /**
     * 生成发送日志
     * @param $mobile
     * @param $type
     * @param $msg
     * @return boolean
     */
    private function generateLog($mobile,$type,$msg)
    {
        $set = ['mobile'=>$mobile,'status'=>0,'msg'=>$msg,'type'=>$type];
        $res = LogSms::create($set);
        if(!$res) return false;
        return $res->id;
    }

    /**
     * 发送短信
     * @param $mobile 手机号
     * @param $template_type 模板编号(查阅配置文件smsTemplate.php)
     * @param $data array 要传的参数(查阅配置文件smsTemplate.php) 如果没有参数可不传
     */
    public function sendMsg($mobile,$template_type,$data=[])
    {
        if(!$template_type || !$mobile)
        {
            throw new ParamsException([
                'error_code' => '1000',
                'message'    => '参数未设置，或为空',
            ]);
        }

        $template = config("smsTemplate.$template_type");
        if(!$template)
        {
            throw new ParamsException([
                'error_code' => '1000',
                'message'    => '模板不存在',
            ]);
        }

        $params_number = substr_count($template,'%s');
        switch ($params_number)
        {//自动将传入的参数赋值到模板,目前最多支持三个参数，如超过需手动添加
            case 1:
                $this->checkParamsNum($data,1);
                $msg = sprintf($template,$data[0]);
                break;
            case 2:
                $this->checkParamsNum($data,2);
                $msg = sprintf($template,$data[0],$data[1]);
                break;
            case 3:
                $this->checkParamsNum($data,3);
                $msg = sprintf($template,$data[0],$data[1],$data[2]);
                break;
            default:
                $msg = $template;
                break;
        }
        $singleSender = new SmsSenderService();
        if(config('app.debug') != true)
        {
            $result = $singleSender->send(0, "86", $mobile, $msg);
            $rsp = json_decode($result);
        }
        else
        {
            $rsp = (object) array('errmsg'=>'OK');
        }

        if ($rsp->errmsg == 'OK')
        {
            $this->generateLog($mobile,0,$msg);
            return true;
        }
        return false;
    }

    /**
     * 验证参数个数是否与传入的参数一至
     * @param $data
     * @param $number
     */
    private function checkParamsNum($data,$number)
    {
        $params_number = count($data);
        if($number != $params_number)
        {
            throw new ParamsException([
                'error_code' => '1000',
                'message'    => '传入的数据数组参数个数与模板参数不符',
            ]);
        }
    }
}